/* A file can already exist (exists) on the filesystem,
   it can be executed (run),
   saved on disk from a webpage content (save).
   The name while being saved on disk is a random number or the hash
   of the url or page content. */

// handle to the preferences
var prefManager = Components.classes["@mozilla.org/preferences-service;1"]
		.getService(Components.interfaces.nsIPrefBranch);

var peercafeFile = {
  exists: function (filename)
    {
      try {
        var nsILocalFile = Components.classes["@mozilla.org/file/local;1"]
			.getService(Components.interfaces.nsILocalFile);
        var nsIFileOutputStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
			.createInstance(Components.interfaces.nsIFileOutputStream);
        nsILocalFile.initWithPath(filename);
        return nsILocalFile.exists();
      }
      catch(ex) {
		alert('Exception in peercafeFile.exists \n' + ex);
        return null;
      }
    },

  // run a file with the given parameters
  run: function (filename, parameter)
    {
      var paramArray = parameter ? parameter.split(/\s+/) : [];
      try {
        var nsILocalFile = Components.classes["@mozilla.org/file/local;1"].getService(Components.interfaces.nsILocalFile);
        var nsIProcess = Components.classes["@mozilla.org/process/util;1"].getService(Components.interfaces.nsIProcess);
        nsILocalFile.initWithPath(filename);
        nsIProcess.init(nsILocalFile);
        nsIProcess.run(false, paramArray, paramArray.length);
        nsIProcess.close();
        return nsILocalFile;
      }
      catch(ex) {
	    alert('Exception in peercafeFile.run \n' + ex);
        return null;
      }
    },

  // save the current url to a file on disk
  save: function (filename, url){
	try {
		_checkFolderExistence();
		var folder = prefManager.getCharPref("extensions.peercafe.loggingFolder"); // in which folder??
		var filePath = folder + filename;
		//alert('going to control and save: ' + filePath);
		if(peercafeFile.exists(filePath)){
			//alert('this page was already copyed');
			return null; // do not copy twice the same page
		} else {
			var nsILocalFile = Components.classes["@mozilla.org/file/local;1"]
				.getService(Components.interfaces.nsILocalFile);
	        var nsIURI = Components.classes["@mozilla.org/network/standard-url;1"]
				.getService(Components.interfaces.nsIURI);
	        nsILocalFile.initWithPath(filePath);
	        nsIURI.spec = url;
	        var nsIWBP = Components.interfaces.nsIWebBrowserPersist;
	        var persist = Components.classes["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
				.createInstance(nsIWBP);
	        persist.persistFlags = nsIWBP.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
			// copy the file from the cache
	        persist.saveURI(nsIURI, null, null, null, null, nsILocalFile);
	        return nsILocalFile;
		}
      } catch(ex) {
		//alert('Exception in peercafeFile.save\n' + ex);
		// this exception can be thrown if the url is null (in the case of a new, empty, tab for example)
        return null;
      }
    }
}

/* Check if the default folder exsists, if not, create it
   this check is done more than once since if the folder gets deleted and the user
   restores the default folder as logging target, the save function will silently
   crash and nothing will be saved on disk. */
function _checkFolderExistence(){
	try{
		var file = Components.classes["@mozilla.org/file/directory_service;1"]
		                     .getService(Components.interfaces.nsIProperties)
		                     .get("Home", Components.interfaces.nsIFile);
		file.append("peercafe");
		if( !file.exists() || !file.isDirectory() ) {   // if it doesn't exist, create
		   file.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0777);
	       //alert('default folder created');
		}
	}catch(ex){
		alert('exception in checkFolderExistence ' + ex);
	}
}

/* some different ways to create a name that will be used while storing the
   content of the current webpage to disk.. the name can be choosen:
   RANDOMLY, HASHED URL, HASHED CONTENT */
function createPageID(innerHtml, location){
	try {
		var type
		
		if(prefManager.getBoolPref("extensions.peercafe.random")){
			//alert('val = 1')
			type = 1
		} else if(prefManager.getBoolPref("extensions.peercafe.hashURL")){
			//alert('val = 2')
			type = 2
		} else if(prefManager.getBoolPref("extensions.peercafe.hashContent")){
			//alert('val = 3')
			type = 3
		} else {
			alert('ERROR in _createfileName, type not selected!!')
		}
		
		switch(type){
			case 3 : { // HASH CONTENT
				return Hex32(Crc32Str(innerHtml));
			}
			case 2 : { // HASH URL
				return Hex32(Crc32Str(location));
			}
			case 1 :{ // RANDOM
				var folder = prefManager.getCharPref("extensions.peercafe.loggingFolder");
				var name = Math.floor(Math.random() * 999999);
				while (peercafeFile.exists(folder + name)){
					++name;
				}
				return name;
			}
			default : return Math.floor(Math.random() * 999999)
		}
	} catch(ex){
		// alert('Exception in _createfileName ' + ex)
		// sometimes the body wont contain HTML, then the hash content will use a
		// random name (since there is no content)
		return Math.floor(Math.random() * 999999)
	}
}

// save the given url (which is the current url that the user is browsing) to a file
function saveHTML(url){
	try {
		var currentState = prefManager.getBoolPref("extensions.peercafe.logging");
		// save the content to file only if the logging status is set to true (green icon)
		if(currentState && !isBlackListed(url)){
			peercafeFile.save(createPageID(window.content.document.body.innerHTML,
				window.content.document.location.href), url); // using a crc32 hash as filename
		} else {
			//alert('content logging is disabled');
		}
	} catch(ex){
		//alert('Exception in saveHTML\n' + ex);
	}
}

